//
//  MapViewController.m
//  Tazama NGO
//
//  Created by jsheriff on 3/2/11.
//  Copyright 2011 The MITRE Corporation. All rights reserved.
//

#import "MapViewController_iPhone.h"
#import "FieldObservationDB.h"
#import "FieldObservationAnnotation.h"
#import "Notifications.h"
#import "ResourceRequisitionDB.h"
#import "ResourceRequisition.h"
#import "ResourceRequisitionAnnotation.h"
#import "KmlElementDB.h"
#import "MTOfflineMapKit.h"
#import "KmlPlacemarkViewController.h"
#import "KMLParser.h"
#import "Settings.h"

@implementation MapViewController_iPhone

@synthesize mapView;
@synthesize centerOnUser;
@synthesize initialUserLocation;
@synthesize currentMapPackPath;

@synthesize toolbar;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

- (IBAction)currLocClick:(id)sender {
    //Center the map on the current location
    if (mapView.userLocation != NULL) {
        [mapView setCenterCoordinate:mapView.userLocation.coordinate animated:YES];
    }
}

-(IBAction)settingsButtonClick:(id)sender {
    
    SettingsViewController *settingsController = [[SettingsViewController alloc] initWithNibName:@"SettingsViewController" bundle:nil];
    settingsController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentModalViewController:settingsController animated:YES];
    [settingsController release];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	mapView.delegate = self;
	mapView.mapType = MKMapTypeHybrid;
	centerOnUser = NO;
	initialUserLocation = YES;
    
    toolbar.barStyle = UIBarStyleType;
    
    [self addMessagesToMap];
    [self addRequestsToMap];
    [self addKmlPlacemarksToMap];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(displayMessageOnMap:) name:kDisplayMessageOnMapNotification object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateMessages:) name:kFieldObservationDatabaseUpdateKey object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateResourceRequisitions:) name:kResourceRequisitionDatabaseUpdateKey object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateKmlPlacemarks:) name:kKmlDatabaseUpdateKey object:nil];
//	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mapSelectionChanged:) name:kMapSelectionChanged object:nil];
    	
    [super viewDidLoad];
}

-(void)addMessagesToMap {
    FieldObservationDB *db = [FieldObservationDB sharedInstance];
	for (FieldObservation *fo in db.fieldObservationList) {
		FieldObservationAnnotation *annotation = [[FieldObservationAnnotation alloc] init];
		annotation.coordinate = fo.location;
		annotation.title = fo.immediateNeeds;
		annotation.fieldObservation = fo;
//		[mapView addAnnotation:annotation];
	}	
}

-(void)addRequestsToMap {
    ResourceRequisitionDB *rrDb = [ResourceRequisitionDB sharedInstance];
	for (ResourceRequisition *rr in rrDb.resourceRequisitionList) {
		ResourceRequisitionAnnotation *annotation = [[ResourceRequisitionAnnotation alloc] init];
		annotation.coordinate = rr.location;
		annotation.title = rr.name;
		annotation.resourceRequisition = rr;
		[mapView addAnnotation:annotation];
	}	    
}

-(void)addKmlPlacemarksToMap {
    [mapView addAnnotations:[KmlElementDB sharedInstance].kmlAnnotationList];
    [mapView addOverlays:[KmlElementDB sharedInstance].kmlOverlayList];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)mapView:(MKMapView *)localMapView didUpdateUserLocation:(MKUserLocation *)userLocation {
	// Filter spurious values
	if (userLocation.coordinate.latitude > 90.0 || userLocation.coordinate.latitude == 0.0 || userLocation.coordinate.longitude < -90.0 || userLocation.coordinate.longitude == 0.0) {
		NSLog(@"didUpdateUserLocation returned bad coordinate");
		return;
	}
	
	if (initialUserLocation || centerOnUser) {
		MKCoordinateRegion region;
		region.center = userLocation.coordinate;
		region.span.latitudeDelta = .06;
		region.span.longitudeDelta = .06;
    
		[mapView setRegion:region animated:YES];
		
		initialUserLocation = NO;
	}
}

-(void)mapSelectionChanged:(NSNotification *)notification {	
	[mapView removeOverlays:mapView.overlays];
	
	if (notification.userInfo == nil) {
		self.currentMapPackPath = nil;
		return;
	}
    
	self.currentMapPackPath = [notification.userInfo objectForKey:@"mapPackPath"];
	
	if (currentMapPackPath == nil) {
		return;
	}
	
	MTOverlayDataSourceMapPack *dataSource = [[MTOverlayDataSourceMapPack alloc] initWithDatabasePath:currentMapPackPath];
	
	// Create the overlay and add it to the map view	
	MTOverlay *overlay = [[MTOverlay alloc] initWithDataSource:dataSource];
	[mapView addOverlay:overlay];
	[overlay release];
}

- (MKAnnotationView *)mapView:(MKMapView *)localMapView viewForAnnotation:(id <MKAnnotation>)annotation {
	if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
	}
	else if ([annotation isKindOfClass:[FieldObservationAnnotation class]]) {
        //		FieldObservationAnnotation *foAnnotation = annotation;
		MKAnnotationView *annotationView = [localMapView dequeueReusableAnnotationViewWithIdentifier:@"FieldObservationAnnotationView"];
		if (annotationView == nil)
		{
			annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"FieldObservationAnnotationView"] autorelease];
		}
		
		annotationView.annotation = annotation;
		UIImageView	 *foImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MagnifyingGlassMarker40.png"]];
		[annotationView addSubview:foImageView];
		annotationView.image = [UIImage imageNamed:@"Transparent33.png"];
		annotationView.canShowCallout = YES;
		[annotationView setRightCalloutAccessoryView:[UIButton buttonWithType:UIButtonTypeDetailDisclosure]];
        annotationView.centerOffset = CGPointMake(0.0, -23.0);
		return annotationView;
	}
	else if ([annotation isKindOfClass:[ResourceRequisitionAnnotation class]]) {
        //		FieldObservationAnnotation *foAnnotation = annotation;
		MKAnnotationView *annotationView = [localMapView dequeueReusableAnnotationViewWithIdentifier:@"ResourceRequisitionAnnotationView"];
		if (annotationView == nil)
		{
			annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"ResourceRequisitionAnnotationView"] autorelease];
		}
		
		annotationView.annotation = annotation;
		UIImageView	 *foImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"QuestionMarkMarker40.png"]];
		[annotationView addSubview:foImageView];
		annotationView.image = [UIImage imageNamed:@"Transparent33.png"];
		annotationView.canShowCallout = YES;
//		[annotationView setRightCalloutAccessoryView:[UIButton buttonWithType:UIButtonTypeDetailDisclosure]];
        annotationView.centerOffset = CGPointMake(0.0, -23.0);
		return annotationView;
	}
    else if ([annotation isKindOfClass:[MKPointAnnotation class]]) {
        MKAnnotationView *annotationView = [[KmlElementDB sharedInstance] viewForAnnotation:annotation];
        annotationView.canShowCallout = YES;
		[annotationView setRightCalloutAccessoryView:[UIButton buttonWithType:UIButtonTypeDetailDisclosure]];
		return annotationView;
    }
	else {
        NSLog(@"annotation class = %@", NSStringFromClass([annotation class]));
		return nil;
	}

}

-(void)displayMessageOnMap:(NSNotification *)notification {
	FieldObservation *fo = [[notification userInfo] objectForKey:kFieldObservationKey];	
	
	for (id<MKAnnotation> annotation in mapView.annotations)
	{
        if ([annotation isKindOfClass:[FieldObservationAnnotation class]]) {
            FieldObservationAnnotation *foAnnotation = (FieldObservationAnnotation *)annotation;
            if (CFEqual(foAnnotation.fieldObservation.uuid, fo.uuid))
            {
                MKCoordinateSpan span = {0.08, 0.08};
                MKCoordinateRegion region = {annotation.coordinate, span};
                [mapView setRegion:region animated:YES];
			
                [mapView selectAnnotation:annotation animated:YES];
			
                self.tabBarController.selectedIndex = 0;
			
                return;
            }
		}
	}
}

-(void)updateMessages:(NSNotification *)notification {
    NSMutableArray *annotationList = [[NSMutableArray alloc] init];
	for (id<MKAnnotation> annotation in mapView.annotations)
	{
        if ([annotation isKindOfClass:[ResourceRequisitionAnnotation class]]) {
            [annotationList addObject:annotation];
        }
    }
    
    [mapView removeAnnotations:annotationList];
    
    [self addMessagesToMap];  
}

-(void)updateResourceRequisitions:(NSNotification *)notification {
    NSMutableArray *annotationList = [[NSMutableArray alloc] init];
	for (id<MKAnnotation> annotation in mapView.annotations)
	{
        if ([annotation isKindOfClass:[ResourceRequisitionAnnotation class]]) {
            NSLog(@"Found ResourceRequisitionAnnotation");
            [annotationList addObject:annotation];
        }
    }
    
    [mapView removeAnnotations:annotationList];
    
    [self addRequestsToMap];
}

-(void)updateKmlPlacemarks:(NSNotification *)notification {
    // Delete the old kml placemarks from the map
    NSMutableArray *annotationList = [[NSMutableArray alloc] init];
	for (id<MKAnnotation> annotation in mapView.annotations)
	{
        if ([annotation isKindOfClass:[MKPointAnnotation class]]) {
            [annotationList addObject:annotation];
        }
    }
    [mapView removeAnnotations:annotationList];
    
    // Add the updated kml placemarks to the map
    [self addKmlPlacemarksToMap];
}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
    if ([view.annotation isKindOfClass:[FieldObservationAnnotation class]]) {
        FieldObservationAnnotation *annotation = view.annotation;
        NSDictionary *userInfo = [NSDictionary dictionaryWithObject:annotation.fieldObservation forKey:kFieldObservationKey];
        [[NSNotificationCenter defaultCenter] postNotificationName:kDisplayMessageDetail object:self userInfo:userInfo];	
    }
    else if ([view.annotation isKindOfClass:[MKPointAnnotation class]]) {
        MKPointAnnotation *pointAnnotation = view.annotation;
        
        // Create the view controller
        KmlPlacemarkViewController *kmlPlacemarkViewController = [[KmlPlacemarkViewController alloc] initWithNibName:@"KmlPlacemarkViewController" bundle:nil];
        kmlPlacemarkViewController.title = pointAnnotation.title;
        
        // Find the matching placemark
        for (KMLPlacemark *placemark in [[[KmlElementDB sharedInstance] kmlParser] _placemarks]) {
            if (placemark.mkShape == pointAnnotation) {
//                NSString *html = @"<html><head><title>The Meaning of Life</title></head><body><p>...really is <b>42</b>!</p></body></html>";
//                kmlPlacemarkViewController.htmlContent = html;
                kmlPlacemarkViewController.htmlContent = placemark.placemarkDescription;
                break;
            }
        }
        
        // Show the view controller
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:kmlPlacemarkViewController];
        navigationController.navigationBar.barStyle = UIBarStyleType;
        
        [self presentModalViewController:navigationController animated:YES];
        [navigationController release];
        [kmlPlacemarkViewController release];
    }
    else
        NSLog(@"calloutAccessoryControlTapped for unknown annotation type");
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
